<template>
    <div class="activity-detail page-content">
        <div class="container">
            <div class="activity-header">
                <h1 class="title">{{ activityTitle }}</h1>
                <div class="metadata">
                    <div class="metadata-item"
                        ><i class="iconfont-sys">&#xe6f7;</i
                        ><span>{{ startTimeFormatted }} - {{ endTimeFormatted }}</span></div
                    >
                    <div class="metadata-item"
                        ><i class="iconfont-sys">&#xe620;</i><span>{{ location }}</span></div
                    >
                    <div class="metadata-item"
                        ><i class="iconfont-sys">&#xe689;</i
                        ><span>浏览量: {{ browseCount }}</span></div
                    >
                    <div class="metadata-item">
                        <el-tag :type="statusType" size="small">{{ statusText }}</el-tag>
                    </div>
                </div>
            </div>

            <div class="activity-content">
                <div class="markdown-body" v-highlight v-html="activityHtml"></div>
            </div>

            <div class="reservation-section">
                <h2>预约情况</h2>
                <p>当前预约人数: {{ reservationList.length }}</p>
                <div class="reservation-list">
                    <el-table v-loading="tableLoading" :data="reservationList" style="width: 100%">
                        <el-table-column prop="userName" label="姓名" width="120" />
                        <el-table-column prop="userSex" label="性别" width="120">
                          <template #default="scope">
                            {{scope.row.userSex == 1 ? '男' : '女'}}
                          </template>
                        </el-table-column>
                        <el-table-column prop="userPhone" label="手机号" width="150" />
                        <el-table-column prop="startTime" label="预约时间" width="180">
                            <template #default="scope">
                                {{ formatDate(scope.row.startTime) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="remark" label="备注" />
                    </el-table>

                    <div class="empty-block" v-if="reservationList.length === 0 && !tableLoading">
                        <el-empty description="暂无预约记录" />
                    </div>

                    <div class="pagination-container" v-if="reservationList.length > 0">
                        <el-pagination
                            v-model:current-page="currentPage"
                            v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 30, 40]"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="totalReservations"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                        />
                    </div>
                </div>
            </div>

            <div class="full-btn-block" v-if="!canReserve && status === 2">
                <el-alert title="此活动预约人数已满" type="warning" :closable="false" show-icon />
            </div>

            <div class="full-btn-block" v-if="status === 3">
                <el-alert title="此活动已结束" type="info" :closable="false" show-icon />
            </div>

            <div class="full-btn-block" v-if="status === 1 && !reservationStarted">
                <el-alert title="活动预约尚未开始" type="info" :closable="false" show-icon />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
    import { ref, computed, onMounted, watch } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    import { ElMessage } from 'element-plus'
    import { useDateFormat } from '@vueuse/core'
    import {
        scenicActivityActivityViewsUsingGet,
        scenicActivityGetActivityByIdUsingPost
    } from '@/api/4a/huodongguanli'
    const route = useRoute()
    const router = useRouter()

    const activityId = ref<any>()
    const activityTitle = ref<string | undefined>('')
    const activityHtml = ref<string | undefined>('')
    const startTime = ref<string | undefined>('')
    const endTime = ref<string | undefined>('')
    const location = ref<string | undefined>('')
    const browseCount = ref<number | undefined>(0)
    const status = ref<number | undefined>(1) // 1:未开始 2:进行中 3:已结束
    const maxParticipants = ref<any>(0)
    const currentParticipants = ref(0)

    // 预约列表相关
    interface Reservation {
        id: number
        activityId: string
        activityTitle: string
        userName: string
        userPhone: string
        reserveTime: string
        status: number
        remark: string
    }

    const reservationList = ref<Reservation[]>([])
    const tableLoading = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const totalReservations = ref<number | undefined>(0)
    // 状态显示
    const statusText = computed(() => {
        switch (status.value) {
            case 1:
                return '未开始'
            case 2:
                return '进行中'
            case 3:
                return '已结束'
            default:
                return '未知'
        }
    })

    // 状态类型
    const statusType = computed(() => {
        switch (status.value) {
            case 1:
                return 'primary'
            case 2:
                return 'success'
            case 3:
                return 'info'
            default:
                return 'info'
        }
    })

    // 格式化时间显示
    const startTimeFormatted = computed(() => {
        return startTime.value ? useDateFormat(startTime.value, 'YYYY-MM-DD HH:mm').value : ''
    })

    const endTimeFormatted = computed(() => {
        return endTime.value ? useDateFormat(endTime.value, 'YYYY-MM-DD HH:mm').value : ''
    })

    // 是否可以预约
    const canReserve = computed(() => {
        return (
            status.value === 2 &&
            currentParticipants.value < maxParticipants.value &&
            reservationStarted.value
        )
    })

    // 预约是否已开始
    const reservationStarted = ref(true)

    // 获取预约状态文本
    const getReservationStatusText = (status: number): string => {
        switch (status) {
            case 1:
                return '待确认'
            case 2:
                return '已确认'
            case 3:
                return '已取消'
            default:
                return '未知'
        }
    }

    // 获取预约状态类型
    const getReservationStatusType = (status: number) => {
        switch (status) {
            case 1:
                return 'warning'
            case 2:
                return 'success'
            case 3:
                return 'info'
            default:
                return 'info'
        }
    }

    // 格式化日期
    const formatDate = (dateString: string): string => {
        return dateString ? useDateFormat(dateString, 'YYYY-MM-DD HH:mm:ss').value : '-'
    }

    // 获取活动详情
    const getActivityDetail = async () => {
        try {
            activityId.value = route.query.id as any
            const res = await scenicActivityGetActivityByIdUsingPost({
                params: {
                    activityId: activityId.value
                }
            })
            if (res.code === 0) {
                activityTitle.value = res.data?.activityName;
                activityHtml.value = res.data?.introduction;
                startTime.value = res.data?.startTime;
                endTime.value = res.data?.endTime;
                location.value = res.data?.location;
                browseCount.value = res.data?.browseCount;
                status.value = res.data?.activityStatus;
                maxParticipants.value = res.data?.maxParticipants;
                currentParticipants.value = res.data?.currentParticipants;
                reservationList.value = res.data?.websiteMenuActivityVoList.ticketingUserFormVo || [];
            }
        } catch (error) {
            console.error('获取活动详情失败', error)
            ElMessage.error('获取活动详情失败')
        }
    }

    // 获取预约列表
    // const getReservationList = async () => {
    //     tableLoading.value = true
    //     // 实际API调用应该类似于下面的代码
    //     try {
    //         const res = await scenicTicketingUserPageTicketingUserFormUsingPost({
    //             activityId: activityId.value,
    //             page: currentPage.value,
    //             size: pageSize.value
    //         })
    //         if (res.code === 0) {
    //             reservationList.value = res.data?.list
    //             totalReservations.value = res.data?.total
    //         }
    //     } catch (error) {
    //         console.error('获取预约列表失败', error)
    //         ElMessage.error('获取预约列表失败')
    //     } finally {
    //         tableLoading.value = false
    //     }
    // }

    // 处理页码大小变化
    const handleSizeChange = (val: number) => {
        pageSize.value = val
        currentPage.value = 1
    }

    // 分页切换
    const handleCurrentChange = (val: number) => {
        currentPage.value = val
    }

    onMounted(() => {
        activityId.value = route.query.id || ''
        getActivityDetail()
        activityScan()
    })

    // 活动浏览活动
    const activityScan = async () => {
        try {
            const res = await scenicActivityActivityViewsUsingGet({
                params: {
                    id: route.query.id as any
                }
            })
            if(res.code !== 0) {
              return ElMessage.error(res.msg)
            }
        } catch (error) {
            console.error('活动浏览活动失败', error)
            ElMessage.error('活动浏览活动失败')
        }
    }

    // 监听路由参数变化
    watch(
        () => route.query.id,
        (newValue) => {
            if (newValue) {
                activityId.value = String(newValue)
                getActivityDetail()
            } else {
                router.push('/activity/list')
            }
        }
    )
</script>

<style lang="scss" scoped>
    .activity-detail {
        .container {
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
        }

        .activity-header {
            margin-bottom: 20px;
            padding-bottom: 20px;
            border-bottom: 1px solid var(--art-border-color);

            .title {
                margin-bottom: 16px;
                font-size: 24px;
                font-weight: 600;
                color: var(--art-text-black);
            }

            .metadata {
                display: flex;
                flex-wrap: wrap;
                gap: 16px;
                color: var(--art-text-gray-600);

                .metadata-item {
                    display: flex;
                    align-items: center;
                    gap: 6px;

                    i {
                        font-size: 16px;
                    }
                }
            }
        }

        .activity-content {
            margin-bottom: 30px;
        }

        .reservation-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid var(--art-border-color);

            h2 {
                margin-bottom: 16px;
                font-size: 20px;
                font-weight: 500;
            }

            p {
                margin-bottom: 20px;
                color: var(--art-text-gray-600);
            }

            .reservation-list {
                margin-top: 20px;
            }

            .empty-block {
                padding: 30px 0;
            }

            .pagination-container {
                margin-top: 20px;
                display: flex;
                justify-content: flex-end;
            }
        }

        .full-btn-block {
            margin-top: 30px;
        }
    }

    @media (max-width: 768px) {
        .activity-detail {
            .activity-header {
                .title {
                    font-size: 20px;
                }

                .metadata {
                    flex-direction: column;
                    gap: 10px;
                }
            }
        }
    }
</style>
